//index.js
//获取应用实例
var Ajax = require('../../utils/Ajax.js')
var utils = require('../../utils/util.js');
var config = require('../../base.conf.js').config;
var smartLock = requirePlugin("smartLock")
const app = getApp();
var ctimeout = null,
  doortime = null;
var nums = null;
Page({
  data: {
    imgurl: app.getApi('download'),
    todayCount:[20,170,321,470],
    isrouter: {
      name: 'home',
      title: '邻里邻外'
    },
    signinobj: '',
    integral: 2,
    isauth:true,//微信运动是否授权
    scopewerun: true,
    count: 2,
    quarters: [],
    isinvitation: false, //是否显示兑换按钮
    getUserStep: null,
    iscertification: false,
    autoplay: false,
    lastopenId: "", //保留上一次小区ID
    banneList: [],
    popupArr: '',
    IntegralInfo: '',
    tipscount: app.getValueSync('tipscount') || 1,
    currentQuarters: '',
    memu: [{
        name: "积分换",
        icon: "icon-icon_-linligou",
        path: "llpurchase",
      },
      {
        name: "拼团购",
        icon: "icon-icon_-pintuangou",
        path: "llgroup",
      },
      {
        name: "星座运势",
        icon: "icon-icon_-xingzuoyunshi",
        path: "constellation"
      },
      {
        name: "更多",
        icon: "icon-icon_-gengduo",
        path: "more"
      }
    ],
    AppkeyList: [],
    door: [{
        name: '西北大门'
      },
      {
        name: '西南大门'
      },
      {
        name: '北大门'
      },
      {
        name: '北大门'
      },
      {
        name: '北大门'
      }
    ],
    integralobj: {
      allIntegral: 0,
      todayIntegralAll: 0,
      todayCount: 0,
      todayIntegras: [0, 0, 0, 0],
      theDay: 0,
      allDay: 7,
      mostIntegral: 8888
    },
    doorName: ''
  },
  onLoad: function(option) {
    // wx.onUserCaptureScreen(function (res) {
    //   console.log(res);
    //   utils.showModal('截屏了吧')
    // })
    this.setData({
      model: app.globalData.model,
      navbarData: {
        title: "首页"
      }
    }, () => {
      this.PlAdvertisLike(10); //更新轮播图
      this.PlAdvertisLike(13); //更新轮播图
      if (app.getValueSync('unionId') != '') {
        this.isFirst();
        this.getIntegralInfo()
        //this.onSignin();
      }
    })
  },
  onHide() {
    this.setData({
      autoplay: false
    })
  },
  onShow() {
    this.isdoor = true;
    this.isrest = true;
    this.cdoortime();
    this.lookgetSetting();

    // 扫描设备
    if (wx.canIUse("getUpdateManager")) {
      const updateManager = wx.getUpdateManager() //更新管理器对象
      updateManager.onCheckForUpdate(function(res) { //向微信后台请求检查更新结果事件的回调函数

      })
      updateManager.onUpdateReady(function() { //小程序有版本更新事件的回调函数
        wx.showModal({
          title: '邻里邻外',
          content: '新版本已经准备好，是否重启应用？',
          success: function(res) {
            if (res.confirm) {
              updateManager.applyUpdate() //强制小程序重启并使用新版本
            } else {
              //TODO刷新一下页面接口
            }
          }
        })
      })
      updateManager.onUpdateFailed(function() { //向微信后台请求检查更新结果事件的回调函数

      })
    }
    if (app.getValueSync('unionId') == '') {
      this.showModal();
    }
  },
  isFirst() { //是否是首次（ps:（这里不跳转手机号码绑定））
    //初始化开锁插件参数
    this.initSmartLockPlus();
    this.refreshDeviceList()
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('蓝牙状态', res)
        if (this.data.AppkeyList == 0) {
          wx.onBluetoothAdapterStateChange((obj) => {
            console.log(obj)
            if (obj.available) {
              console.log('蓝牙已打开')
              this.data.AppkeyList.length == 0&&this.refreshDeviceList();
            } else {
              console.log('蓝牙已关闭')
            }
          })
        }
      },
      fail:(error)=>{
        console.log(error)
        if (this.data.AppkeyList==0){
          wx.onBluetoothAdapterStateChange((obj) => {
            console.log(obj)
            if (obj.available) {
              console.log('蓝牙已打开')
              this.data.AppkeyList.length == 0 && this.refreshDeviceList();
            } else {
              console.log('蓝牙已关闭')
            }
          })
        }
      }
    })
    this.setData({
      weChatInfo: utils.getWechatInfo(), //获取微信用户信息
    })
    if ((app.getValueSync('tipscount') || 1) == 1) { //还未进入引导
      this.showModal('firstScreen');
    } else { //不是首次
      this.isbinding();
    }
  },
  isbinding() { //查看是否有绑定
    this.setData({
      userInfo: utils.getUserInfo(),
      getUserStep: utils.getUserStep() || null,
    }, () => {
      this.judeIsBindPhone(true); //flag==true 去查询已经绑定了手机号码查询已认证小区列表；（没绑定这里不跳转手机号码绑定）
    })
  },
  onOpendoor() { //点击开门
    if (app.getValueSync('unionId') == '') { //可能没有unionId();
      this.showModal()
    } else {
      var {
        userInfo,
        iscertification,
        currentQuarters
      } = this.data;
      if (userInfo) { //如果已经绑定，已经请求到小区;
        if (currentQuarters) {
          if (!this.isdoor) {
            return utils.showLoading('正在操作...')
          }
          this.isopenDoor(currentQuarters); //判断认证的小区是否可以开门
        } else { //还没绑定小区
          utils.toPage(`/pages/certification/certification?isposition=1`)
        }
      } else { //数据错误的情况
        this.judeIsBindPhone(); //查询用户信息
      }
    }
  },
  isopenDoor(currentQuarters) { //绑定了小区判断是否可以开门
    var {
      typeNo
    } = currentQuarters;
    //1:物业通过认证；2物业待审批；3物业拒绝认证;4押金待认证；5 押金认证通过;6证件认证通过；7证件认证待审批；8证件认证拒绝；9 待认证(申请后还没有选择认证);10 禁止用户开门
    if (typeNo == 1 || typeNo == 5 || typeNo == 6) {
      this.clickOpenDoor(); //去开门
    } else {
      if (typeNo == 10) {
        utils.showtoast('物业已禁止您的开门权限,请联系物业处理')
      } else if (typeNo == 2 || typeNo == 7){
        utils.showtoast('您的认证申请正在审核中，如有问题，请联系物业处理')
      } else if (typeNo == 3 || typeNo == 8) {
        utils.showtoast('您的小区认证未通过，请重新提交或联系物业处理',null,null,true);
        wx.showModal({
          title: '邻里瓴外',
          content: '您的小区认证未通过,是否重新提交',
          success(res) {
            if (res.confirm) {
              utils.toPage(`/pages/certification/certification?` + utils.queryconcat(currentQuarters))
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      } else {
        utils.showtoast('您的小区认证未通过，请联系物业处理')
      }
    }
  },
  switchTab(e) { //tab切换
    var {
      name,
      title
    } = e.currentTarget.dataset;
    if (wx.setNavigationBarTitle) {
      wx.setNavigationBarTitle({
        title: title,
      })
    }
    if (name == "me") {
      this.onintegral() //查询签到信息
    }
    this.setData({
      isrouter: {
        "name": name,
        "title": title
      }
    })
  },
  getIntegralInfo() { //获取积分规则
    Ajax.get('getIntegralInfo').then((d) => {
      if (d.code == 0) {
        this.setData({
          IntegralInfo: d.data
        })
      }
    }).catch((e) => {
      console.log(e)
    })
  },
  judeIsBindPhone(flag = false) {
    var unionId = app.getValueSync('unionId') || '';
    Ajax.get('judeIsBindPhone', {
      unionId,
    }).then((d) => {
      if (d.status == 200) { //存储用户信息
        app.saveSync('user_info', JSON.stringify(d.data))
        this.setData({
          userInfo: d.data
        }, () => { //查询已认证的小区
          this.getAllQuartersByUserId(flag); //有用户信息再去查询是否绑定了小区
        })
      } else {
        if (d.status == 500) { //是否绑定了手机
          if (!flag) { //flag为false就不跳转绑定手机页面
            utils.showtoast(d.message || '请绑定手机号', null, null, true)
            setTimeout(() => {
              utils.toPage(`/pages/bindingphone/bindingphone`)
            }, 1500)
          }
        } else {
          console.log(d)
        }
      }
    }).catch((e) => {
      console.log(e)
    })
  },
  getAllQuartersByUserId(flag = false) { //查询已认证的小区
    var {
      userInfo,
      currentQuarters
    } = this.data;
    Ajax.get("getAllQuartersByUserId", {
      userId: userInfo.id
    }).then((d) => {
      // 返回的小区列表为空  
      if (d.status == 200) {
        var list = d.data || [];
        currentQuarters = '';
        var lastopenId = app.getValueSync('lastopenId'); //选择的小区ID
        for (var i = 0; i < list.length; i++) {
          if (lastopenId) { //是否存在
            if (list[i].requId == lastopenId) { //选好的小区
              currentQuarters = list[i]
              break;
            }
          } else { //默认选择第一个小区
            currentQuarters = list[0];
            app.saveSync('lastopenId', currentQuarters.id);
            break;
          }
        }
        if (list.length && currentQuarters == '') { //处理以前的小区被后台删除
          currentQuarters = list[0];
          app.saveSync('lastopenId', currentQuarters.id);
        }
        this.setData({
          currentQuarters: list.length ? currentQuarters : '',
          quarters: list,
          iscertification: list.length ? true:false,
        }, () => {
          var {
            currentQuarters
          } = this.data;
          if (currentQuarters && flag == false) {
            if (!this.isdoor) {
              return utils.showLoading('正在操作...')
            }
            this.isopenDoor(currentQuarters); //判断认证的小区是否可以开门
          } else {
            if (flag == false) { //
              utils.toPage(`/pages/certification/certification?isposition=1`)
            }
          }
        })
      } else {
        utils.showtoast(d.message || '服务器出错')
      }
    }).catch((e) => {
      console.log(e)
    })
  },
  refresh() { //刷新
    this.getIntegralInfo();
    if (this.data.isrouter.name == 'home') { //在我的页面积分记录更新
      this.PlAdvertisLike(10); //更新轮播图
      this.PlAdvertisLike(13); //更新轮播图
    }
    var getUserStep = utils.getUserStep();
    this.data.userInfo&&this.getAllQuartersByUserId(true); //有用户信息再去查询是否绑定了小区
    if (getUserStep && getUserStep.uuid) {
      this.updateSysStep(); //跟新步数
    } else {
      wx.stopPullDownRefresh();
    }

  },
  PlAdvertisLike(position) { //查询轮播图
    var that = this;
    if (position == 10) {
      this.setData({
        autoplay: false
      })
    }
    Ajax.post("PlAdvertisLike", {
      area: "1", //平台
      position: position, //首页轮播
    }).then((d) => {
      wx.stopPullDownRefresh();
      // utils.hideLoading()
      var imglist = d.data;
      if (d.status == 200) {
        var temp = position == 10 ? "banneList" : "popupArr";
        if (temp == "banneList") {
          this.selectComponent("#Mswiper").setswiperIndex()
          this.setData({
            autoplay: true
          })
        }
        that.setData({
          [temp]: imglist
        })
      } else {
        utils.showtoast(d.msg)
      }
    }).catch((e) => {
      wx.stopPullDownRefresh();
      console.log(e)
      // utils.hideLoading()
      utils.showtoast('网络错误,数据加载失败')
    })
  },
  //开门广告
  toadvertising(e) {
    //链接类型: 1H5 2内部商品详情 3内部分类 4内部主题热卖 5外部链接(其他小程序)
    var {
      item,
      item: {
        linkType,
        link
      }
    } = e.currentTarget.dataset;
    var title = item.title || '邻里邻外';
    if (linkType == 1) {
      this.closeModal('openDoor')
      url = "/pages/mywebview/mywebview?title=" + title + "&url=" + link
      utils.toPage(url)
    } else if (linkType == 2) {
      this.closeModal('openDoor')
      url = "/pages/goodsmain/goodsmain?" + link
      utils.toPage(url)
    } else if (linkType == 5 || linkType == 3) {
      //跳转小程序
      this.closeModal('openDoor')
      var url = linkType == 5 ? ("/pages/goodsmain/goodsmain?" + link) : ("/pages/goodslist/goodslist?" + link)
      wx.navigateToMiniProgram({
        appId: 'wxc1879cc38dea6b92',
        path: url,
        envVersion: config.isDebug ? 'trial' : 'release',
        success(res) {
          console.log(res)
        },
        fail(res) {
          console.log(res)
        }
      })
    } else {
      console.log(e)
      link && link != '/' && utils.toPage(item.link) && this.closeModal('openDoor');
    }
  },
  onPullDownRefresh: function() { //下拉刷新
    this.refresh()
  },
  //没有UID弹窗
  showModal(id) {
    var modal = this.selectComponent("#" + (id || 'noUid'));
    modal.show();
  },
  closeModal(e) { //关闭弹窗
    var id = this.onSetid(e);
    var modal = this.selectComponent("#" + (id || 'noUid'));
    modal.hide();
  },
  onSetid(e) { //弹出窗的ID获取
    var id = 'modal'
    if (typeof(e) == 'string') {
      id = e
    } else {
      id = e && (e.currentTarget.id || e.currentTarget.dataset.id);
    }
    return id;
  },
  onTappages(e) { //me跳转页面
    var {
      path
    } = e.currentTarget.dataset;
    var {
      currentQuarters,
      isauth
    } = this.data;
    if (path == 'seltelcommunity') {
      var quartersName = currentQuarters && currentQuarters.quartersName || '';
      utils.toPage(`/pages/${path}/${path}` + (quartersName ? ('?quartersName=' + quartersName) : ''))
    } else if (path == 'llpurchase') {
      utils.toPage(`/pages/${path}/${path}?isauth=${isauth ? 1 :0}`)
    }else{
      utils.toPage(`/pages/${path}/${path}`)
    }
  },
  onTips() { //首次进入引导
    var {
      tipscount
    } = this.data;
    this.setData({
      tipscount: ++tipscount
    }, () => {
      if (this.data.tipscount > 1) {
        this.selectComponent("#firstScreen").hide();
        this.selectComponent("#firstScreenNext").show();
      }
      if (this.data.tipscount > 2) {
        app.saveSync('tipscount', tipscount)
        this.selectComponent("#firstScreenNext").hide();
        this.isbinding();
      }
    })
  },
  cancel() { //关闭兑换积分
    this.closeModal('Model')
  },
  onClose() { //关闭兑换提示
    this.closeModal('isExchange');
  },
  judgeWeRun() { //判断用户是否初始化步数
    var {
      getUserStep,
      scopewerun
    } = this.data;
    getUserStep = getUserStep || {}
    if (!getUserStep.uuid && app.getValueSync('unionId') && scopewerun) { //特殊情况判断是否有uuid
      app.getWeRun((status, msg) => {
        if (status) {
          this.setData({
            getUserStep: msg.data
          }, () => {
            this.updateSysStep(); //更新步数
          })
        }
      }, false, false) //初始化步数
    } else if (getUserStep.uuid) {
      this.updateSysStep();
    }
  },
  updateSysStep(flag=false) { //更新系统步数
    var {
      getUserStep,
      isauth,
      scopewerun
    } = this.data;
    if (getUserStep && !scopewerun ) { //如果授权过但是没有授权步数
      if (flag==false){
        app.updataStep((status, msg) => { //没有步数更新信息
          this.setData({
            getUserStep: msg.data,
          })
          utils.hideLoading();
          wx.stopPullDownRefresh();
        }, null, true)
      }else{
        app.getWeRun((status, msg) => {
          if (status) {
            this.setData({
              scopewerun: true,
              isauth: true,
              getUserStep: msg.data
            })
            wx.stopPullDownRefresh();
          }},true,false)
      }
      return;
    } else if (getUserStep && scopewerun && isauth) {
      app.getWeRun((status, msg) => {
        utils.hideLoading();
        if (status) {
          this.setData({
            scopewerun: true,
            getUserStep: msg.data
          })
          wx.stopPullDownRefresh();
        } else {
          if (msg && msg.ststus == '该用户不存在或未授权') {
            utils.showLoading();
            wx.removeStorageSync('sysStep')
            this.setData({
              getUserStep: ''
            }, () => {
              wx.stopPullDownRefresh();
              setTimeout(() => {
                this.judgeWeRun();
              }, 500)
            })
          }else{
            if (msg && msg.data =='微信运动未授权'){
              this.setData({
                scopewerun: false,
                isauth:false
              })
            }else{
              this.setData({
                scopewerun: false,
                isauth: true
              })
            }
          }
        }
      }, true,false);
    }else{
    }
  },
  lookgetSetting() { //查看步数授权状态
    var { isauth}=this.data;
    isauth&&wx.getSetting({
      success: (res) => {
        this.setData({
          scopewerun: res.authSetting['scope.werun'] || false,
          tipscount: app.getValueSync('tipscount') || 1,
          getUserStep: utils.getUserStep() || null,
        }, () => {
          var {
            getUserStep
          } = this.data;
          console.log(this.data.scopewerun)
          if (getUserStep) {
            this.updateSysStep();
          }
        })
      },
      fail:(e)=>{
      console.log(e)
      }
    })
  },
  remind() { //步数兑换弹窗
    clearTimeout(ctimeout);
    return;
    var {
      getUserStep,
      isrouter: {
        name
      },
      count,
      scopewerun
    } = this.data;
    var timer;
    //没有步数授权，未打开步数授权，没有步数信息或者步数低于3000不提醒兑换
    console.log(getUserStep == null || name != 'home' || (getUserStep && getUserStep.sysStep <= 0) || scopewerun == false)
    if (getUserStep == null || name != 'home' || (getUserStep && getUserStep.sysStep <= 0) || scopewerun == false) {
      return;
    }
    do {
      var out = Math.floor(Math.random() * 7000);
    }
    while (out < 1000) {
      timer = out;
    };
    var cunmttime = new Date().getTime();
    var Timeval = wx.getStorageSync('tipsTime') || '0_0'; //最后次数// @每天1开始自加到3截止 _ @时间戳;
    var numbers = Timeval.split('_')[0];
    var lastTime = Timeval.split('_')[1];
    if (cunmttime - lastTime < 0) {
      lastTime = cunmttime;
      numbers = 0;
    };
    this.setData({
      isinvitation: false
    }, () => {
      console.log(numbers, count, cunmttime - lastTime, cunmttime, lastTime)
      if (numbers < count && cunmttime - lastTime < 86400000) {
        ctimeout = setTimeout(() => {
          this.showModal('isExchange');
        }, timer)
        app.saveSync("tipsTime", ++numbers + '_' + (Number(lastTime) || new Date().getTime()));
      } else if (numbers < count && cunmttime - lastTime > 86400000) {
        var dsys = (cunmttime - lastTime) / 86400000;
        this.showModal('isExchange');
        app.saveSync("tipsTime", '1_' + (dsys < 1 ? Number(lastTime) : new Date().getTime()));
      } else if (numbers >= count && cunmttime - lastTime > 86400000) {
        app.saveSync('tipsTime', '1_' + new Date().getTime());
        ctimeout = setTimeout(() => {
          this.showModal('isExchange');
        }, timer)
      } else if (numbers >= count && cunmttime - lastTime < 86400000) {
        if (numbers < (count + 1)) {
          app.saveSync("tipsTime", ++numbers + '_' + lastTime);
        }
      }
    })

  },
  Tapquantum() { //点击步数兑换
    clearTimeout(ctimeout);
    var {
      getUserStep,
      scopewerun
    } = this.data;
    if (!scopewerun && getUserStep && getUserStep.sysStep == 0) { //没有授权步数
      this.updateSysStep(true);
      return
    }
    if (!getUserStep.sysStep) { //没有步数信息或者步数为0
      this.setData({
        isinvitation: true
      }, () => {
        this.showModal('isExchange');
      })
    } else {
      if (getUserStep && getUserStep.sysStep < 0) {
        return utils.showtoast('数据错误')
      }
      this.setData({
        preview: utils.multiply(getUserStep.convertRate || 0, getUserStep.sysStep || 0)
      }, () => {
        this.setData({
          isinvitation: false
        }, () => {
          this.showModal('isExchange');
        })
      })
    }
  },
  toConfirmchang() {
    this.closeModal("isExchange");
    utils.showLoading();
    setTimeout(() => {
      this.showModal('Model')
      utils.hideLoading();
    }, 500)
  },
  onConfirmchang() { //确认兑换积分
    var {
      getUserStep
    } = this.data;
    if (getUserStep && getUserStep.sysStep > 0) {
      utils.showLoading();
      Ajax.post("exchangeBee", {
        uuid: getUserStep.uuid
      }).then((d) => {
        this.closeModal('Model')
        utils.hideLoading();
        if (d.status == 200 && d.code == 0) {
          this.setData({
            ['getUserStep.integral']: d.data.total,
            ['getUserStep.sysStep']: 0
          }, () => {
            utils.showtoast('兑换成功')
            app.save("sysStep", JSON.stringify(this.data.getUserStep));
          })
        } else {
          utils.showtoast(d.data || d.msg || d.message || '服务器错误,请稍后重试')
        }
      }).catch((e) => {
        utils.hideLoading();
        utils.showtoast('兑换失败，请检查您的网络')
        this.closeModal('isExchange')
      })
    } else {
      this.closeModal('isExchange');
      utils.showtoast('没有可兑换的步数,去邀请好友赠送步数吧')
    }
  },
  /**
   * 初始化开锁插件
   */
  initSmartLockPlus: function() {
    var that = this
    //initSmartLock 中需要5个参数，分别为：appid，appkey，二次开发者登陆dms的账号、二次开发者登陆dms的密码，初始化回调函数。前四个参数请微信联系18988768327或者13530382506获取
    smartLock.initSmartLock("A80C1A90A90C4260B52CB8FE559F70BD", "2A3EFBCE80C8488AA35FE70C37114C77", "13800000001", "123456", function(res) {
      console.log("初始化开锁返回结果：" + res)
    })
  },
  clickOpenDoor: function() { //判断是否能开锁
    //蓝牙开锁
    wx.openBluetoothAdapter({
      success: (res) => {
        this.forLockId();
      },
      fail: (err) => {
        return utils.showtoast('未开启蓝牙，无法使用开门服务 请打开手机蓝牙功能')
      }
    })
  },
  cdoortime() {
    if (!this.isdoor) {
      utils.showtoast('附近没有发现智能门禁设备')
    }
    this.isdoor = true;
    clearTimeout(doortime);
  },
  forLockId() { //轮循查询ID
    var {
      AppkeyList,
      currentQuarters: {
        bindingEquipmentAreas
      }
    } = this.data;
    var currentEquipments = bindingEquipmentAreas;
    var scanLock = AppkeyList //搜索到的蓝牙设备;
    if (scanLock.length > 0) {
      var lockId = ''; //设备id
      var lockName = ''; //设备名称
      for (var a in currentEquipments) {
        for (var b in scanLock) {
          if (currentEquipments[a].id == scanLock[b].LOCKID) {
            lockId = currentEquipments[a].id;
            lockName = currentEquipments[a].nickname;
            break;
          }
        }
      }
      if (!lockId) {
        utils.showtoast('附近没有发现智能门禁设备')
        this.refreshDeviceList();
        this.cdoortime();
      } else { //查询到lockId
        this.setData({
          lockId,
          lockName,
        }, () => {
          if (!this.isrest) {
            return utils.showtoast('操作过于频繁,请在' + this.num + '秒后重试')
          }
          this.isdoor = false;
          doortime = setTimeout(() => { //防止其他错误
            this.cdoortime();
          }, 10000)
          this.openokdoor(this.data.lockId);
        })
      }
    } else {
      utils.showtoast('附近没有发现智能门禁设备');
      this.cdoortime();
      this.refreshDeviceList();
    }
  },
  onSignin() { //保存开门记录签到
    var {
      lockId,
      lockName,
      userInfo,
      currentQuarters,
      getUserStep,
      weChatInfo,
    } = this.data;
    var unionId = app.getValueSync('unionId') || '';
    var openId = app.getValueSync("openid") || '';
    Ajax.post('uploadSwipingCardLog', {
      reqId: currentQuarters.requId,
      userId: userInfo.id,
      deviceId: lockId,
      deviceNickname: lockName,
      unionId,
    }).then((d) => {
      if (d.status == 200 && d.data && JSON.stringify(d.data) != "{}") {
        getUserStep && getUserStep.uuid && this.updateSysStep();
        if (this.data.isrouter.name == 'me') { //在我的页面积分记录更新
          this.onintegral()
        }
        this.setData({
          signinobj: d.data
        }, () => {
          this.showModal('openDoor')
        })
      } else {
        console.log("----")
        console.log(d)
      }
    }).catch((e) => {
      console.log(e)
    })

  },
  onintegral() { //查询签到
    var {
      weChatInfo
    } = this.data;
    var unionId = app.getValueSync('unionId') || '';
    var openId = app.getValueSync("openid") || '';
    if (!unionId) {
      return;
    }
    Ajax.get('integral', {
      unionId,
      openId
    }, {
      "content-type": "application/json;charset=UTF-8",
    }).then((d) => {
      if (d.status == 200 && d.data) {
        console.log(d)
        this.setData({
          integralobj: d.data
        })
      } else {
        console.log(d)
      }
    }).catch((e) => {
      console.log(e)
    })

  },
  openokdoor(lockId) { //拿到设备号开锁
    utils.showLoading();
    smartLock.openCloseBleLock(lockId, '12345678', 1, (res) => {
      // console.error("smartLock openCloseBleLock result: " + JSON.stringify(res.data))
      if (res.data.result == 0) {
        utils.hideLoading();
        this.isdoor = true;
        this.isrest = false;
        this.cdoortime();
        utils.showtoast('开门成功');
        this.num = 6;
        clearInterval(nums);
        nums = setInterval(() => {
          this.num--;
          if (this.num == 0) {
            clearInterval(nums);
            this.isrest = true;
          }
        }, 1000)
        this.onSignin();
      } else {
        this.isdoor = true;
        this.cdoortime();
        wx.showToast({
          title: res.data.msg,
          duration: 1500
        })
      }
    })
  },
  refreshDeviceList: function() {
    var that = this
    smartLock.scanSmartLock(this.scanDeviceCallBack)
  },

  /**
   * 扫描设备回调
   */
  scanDeviceCallBack: function(res) {
    var that = this;
    var dev = res.data.msg
    var deviceName = dev.name
    var rssi = dev.RSSI
    var lockId = smartLock.parseDeviceId(deviceName);
    var deviceType = smartLock.parseDeviceType(deviceName);
    var devName = smartLock.parseDeviceName(deviceName);
    var lock = {
      "LOCKID": lockId,
      "RSSI": rssi,
      "DATA": {
        KEYLOCKID: lockId,
        KEYUSERNAME: devName,
        DEVICETYPE: deviceType
      }
    }
    var lockList = that.data.AppkeyList;
    //获取当前设备列表的id列表
    var lockIdList = lockList.map(function(item) {
      return item.LOCKID;
    })
    if (lockIdList.indexOf(lockId) < 0) {
      //验证当前lock是否在列表里,如果不在,则添加
      lockList.push(lock);
    } else {
      //如果在,则更新
      lockList.splice(lockIdList.indexOf(lockId), 1, lock);
    }
    that.setData({
      AppkeyList: lockList
    })
  },
  //个人中心部分

  //选择大门
  chooseDoor(e) {
    var setItem = e.currentTarget.dataset.item
    this.setData({
      doorName: setItem.name
    })
    this.closeModal('changeDoor')
    this.showModal('doorcode-modal')
  },
  //复制开门邀请码
  copyFn() {
    var that = this
    wx.setClipboardData({
      data: this.data.doorName + '临时开门密码：' + '123456' + '(30分钟内有效)',
      success: function(res) {
        wx.getClipboardData({
          success: (res) => {
            utils.showtoast("已复制");
            that.closeModal('doorcode-modal')
          }
        })
      }
    })
  },
  //页面跳转
  gotoUserinfo() {
    var {
      iscertification
    } = this.data;
    utils.toPage(`/pages/personalInfo/personalInfo?isCertification=${iscertification ? 1:0}`)
  },
  goToPage(e) {
    var pageType = e.currentTarget.dataset.type;
    if (pageType == 1) {
      utils.toPage('/pages/addresspages/addressList/addressList')
    } else if (pageType == 2) {
      var {
        iscertification
      } = this.data;
      if (iscertification) {
        this.showModal('changeDoor')
      } else {
        utils.showtoast('您还没有认证小区哦!')
        return
      }
    } else if (pageType == 4 || pageType == 5) {
      var path = 'pages/order/order/order?currenttab=0'
      if (pageType == 5) {
        console.log('退款售后')
        path = 'pages/order/applyrefundlist/applyrefundlist'
      }
      wx.navigateToMiniProgram({
        appId: 'wx8407e4c0b132614a',
        path,
        envVersion: config.isDebug ? 'trial' : 'release',
        success(res) {
          utils.hideLoading();
        },
        fail(res) {
          console.log(res)
        }
      })
    }
    //  else if (pageType != 3) {
    //   utils.toPage('/pages/certification/certification?isposition=1')
    // }
  },
  lookrules(e) {
    this.showModal('RulesA')
  },
  onShareAppMessage(e) {
    var {
      isrouter
    } = this.data;
    console.log(e)
    if (e.from == "button") {
      var {
        name
      } = e.target.dataset;
      if (name == "invitation") {
        this.closeModal('isExchange');
        var getUserStep = utils.getUserStep() || null;
        var weChatInfo = utils.getWechatInfo() || null;
        if (weChatInfo && getUserStep) {
          return {
            title: `${weChatInfo && weChatInfo.userInfo.nickName || '他'}发起了捐赠步数换礼物，快来帮TA！`,
            path: `/pages/sponsorship/sponsorship?uuid=${getUserStep.uuid}&shareId=${getUserStep.shareId || ''}`,
            imageUrl: '../../assets/img/step.png',
          }
        }

      } else {
        var title = this.data.doorName + '临时开门密码：' + '123456' + '(30分钟内有效)'
        this.closeModal('doorcode-modal');
        return {
          title: title,
          path: `/pages/index/index`,
          imageUrl: '../../assets/img/door-share.png'
        }
      }

    } else {
      return {
        title: '邻里邻外',
        path: `/pages/index/index`,
        imageUrl: '../../assets/img/door-share.png'
      }
    }
  }
})